<template>
    <div class="choreography-page">
        <span class="article-title">编排记录</span>
        <div class="fliter">
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">文章分类：</span>
                <el-cascader style="width: 200px;" clearable v-model="filterParams.articleCategoryId" filterable
                    :options="categoryOptions" :props="categoryProps" placeholder="请选择文章分类" />
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width:60px;">文章数量：</span>
                <el-input type="number" v-model="filterParams.articleCount" style="width: 200px;" placeholder="请输入文章数量"
                    clearable />
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">所属网站：</span>
                <el-select v-model="filterParams.siteId" style="width: 200px;" placeholder="请选择所属网站" clearable
                    filterable>
                    <el-option v-for="item in siteOptions" :key="item.id" :label="item.siteName" :value="item.id" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">文章语言：</span>
                <el-select v-model="filterParams.langId" style="width: 200px;" placeholder="请选择语言" clearable filterable>
                    <el-option v-for="item in languageOptions" :key="item.id" :label="item.langName" :value="item.id" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">文章面向地区：</span>
                <el-select v-model="filterParams.area" style="width: 200px;" placeholder="请选择面向地区" clearable filterable>
                    <el-option v-for="item in countryOptions" :key="item.label" :label="item.label"
                        :value="item.label" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">创建人：</span>
                <el-select v-model="filterParams.createUserId" style="width: 200px;" placeholder="请选择创建人" clearable>
                    <el-option v-for="item in accountNameOptions" :key="item.id" :label="item.username" :value="item.id" />
                </el-select>
            </div>
            <div class="filter-item">
                <span class="filter-label" style="font-size: 14px;min-width: 70px;">创建时间：</span>
                <el-date-picker v-model="filterParams.createTime" style="width: 400px;" placeholder="请选择创建时间" clearable
                    type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                    date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
            </div>
            <div class="filter-item">
                <el-button type="primary" :icon="Search" @click="getChoreographyData">查询</el-button>
            </div>
        </div>
        <div class="article-table">
            <el-button type="primary" @click="getChoreographyData()"><el-icon>
                    <RefreshRight />
                </el-icon> 刷新</el-button>
            <el-table :data="tableData" v-loading="loading"
                :header-cell-style="{ background: '#fafafa', height: '56px', }"
                style="width: 100%;margin-top: 20px;margin-bottom: 20px; height: calc(100% - 70px);">
                <el-table-column type="expand">
                    <template #default="props">
                        <div class="collapse-content-wrapper" v-if="props.row.articleRecordList.length > 0">
                            <div class="collapse-content" v-for="(item, index) in props.row.articleRecordList"
                                :key="index">
                                <div class="content-header">
                                    <h4 class="content-title">{{ item.title }}</h4>
                                </div>
                                <div class="content-body">
                                    <div class="article-outline">
                                        <h5>文章大纲</h5>
                                        <ol class="outline-list">
                                            <li v-for="(_item, _index) in JSON.parse(item.outline)?.introduction"
                                                :key="_index">{{
                                                    _item }}
                                            </li>
                                        </ol>
                                    </div>

                                    <div class="article-status">
                                        <div class="status-item">
                                            <span class="label">开始时间:</span>
                                            <span class="value">{{ dayjs(item.startTime).format('YYYY-MM-DD HH:mm')
                                                }}</span>
                                        </div>
                                        <div class="status-item">
                                            <span class="label">文章状态:</span>
                                            <span class="value status-writing">{{ item.status }}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="collapse-content-wrapper"
                            style="display: flex;justify-content: center;align-items: center;padding: 40px 0;" v-else>
                            <span style="color: #909399;">No data</span>
                        </div>
                    </template>
                </el-table-column>
                <template v-for="(item, index) in tableHeader" :key="index">
                    <el-table-column :prop="item.prop" :label="item.label" :min-width="item.width">
                        <template #default="scope">
                            <span v-if="item.prop === 'insertType'">{{ scope.row?.insertType == 1 ? 'AI运营' : 'AI投流'
                                }}</span>
                            <span v-else-if="item.prop === 'createUserId'">{{ getAccountName(scope.row?.createUserId)
                                }}</span>
                            <span v-else-if="item.prop === 'createTime'">{{
                                dayjs(scope.row[item.prop]).format('YYYY-MM-DD HH:mm:ss') }}</span>
                            <span v-else>{{ scope.row[item.prop] }}</span>
                        </template>
                    </el-table-column>
                </template>
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="scope">
                        <div style="display: flex;align-items: center;gap: 15px;">
                            <span style="cursor: pointer;color: #1677ff;" @click="handleEdit(scope.row.id)">编辑</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                style="display: flex;justify-content: end;" layout="total,prev, pager, next,sizes" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 任务配置组件 -->
        <TaskConfiguration ref="taskConfigRef" />
        <TaskConfiguration1 ref="taskConfig1Ref" />
    </div>
</template>

<script setup lang="ts">
import { defineComponent, onActivated, ref } from 'vue';
defineComponent({ name: 'Choreography' })
import service from '../config';
import { ElMessage } from 'element-plus';
import { RefreshRight, Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { countryOptions } from '../tool';
import TaskConfiguration from '../components/taskConfiguration.vue';
import TaskConfiguration1 from '../components/taskConfiguration1.vue';
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const tableData = ref([])
const categoryOptions = ref([])
const siteOptions = ref([])
const languageOptions = ref([])
const categoryProps = {
    checkStrictly: true,
}
const accountNameOptions = ref([])
const getAccountName = (id) => {
    return accountNameOptions.value.find(item => item.id === id)?.username
}
const filterParams = ref({
    articleCategoryId: null,
    articleCount: null,
    siteId: null,
    langId: null,
    area: null,
    createTime: null,
    createUserId: null,
})
const total = ref(0)
const taskConfigRef = ref()
const taskConfig1Ref = ref()
const tableHeader = ref([
    { label: '文章分类', prop: 'articleCategory', width: 200 },
    { label: '文章数量', prop: 'articleCount', width: 150 },
    { label: '文章类型', prop: 'insertType', width: 150 },
    { label: '完成状态', prop: 'status', width: 200 },
    { label: '所属网站', prop: 'site', width: 200 },
    { label: '文章语言', prop: 'lang', width: 160 },
    { label: '文章面向地区', prop: 'area', width: 200 },
    { label: '创建人', prop: 'createUserId', width: 250 },
    { label: '创建时间', prop: 'createTime', width: 160 },
])

const getChoreographyData = () => {
    loading.value = true
    if (filterParams.value.createTime && Array.isArray(filterParams.value.createTime) && filterParams.value.createTime.length === 2) {
        filterParams.value.createTime = [
            dayjs(filterParams.value.createTime[0]).format('YYYY-MM-DD HH:mm:ss'),
            dayjs(filterParams.value.createTime[1]).format('YYYY-MM-DD HH:mm:ss')
        ]
    }
    service.post('/arrangeRecord/page', { pageNum: pageNum.value, pageSize: pageSize.value, ...filterParams.value, articleCategoryId: filterParams.value.articleCategoryId?.[filterParams.value.articleCategoryId?.length - 1] })
        .then(response => {
            loading.value = false
            tableData.value = response.data?.records
            total.value = response?.data?.total
        })
        .catch(error => {
            loading.value = false
            ElMessage.error(error)
        });
}

const handleSizeChange = () => {
    pageNum.value = 1
    getChoreographyData()
}

const handleCurrentChange = () => {
    getChoreographyData()
}

const handleEdit = (id) => {
    // 根据 id 查找对应的行数据
    const rowData = tableData.value.find(item => item.id === id)
    if (!rowData) {
        ElMessage.error('未找到对应的数据')
        return
    }
    // 根据 insertType 决定打开哪个弹窗
    if (rowData.insertType == 1) {
        // 打开 taskConfiguration.vue
        taskConfigRef.value?.openModal(rowData)
    } else {
        // 打开 taskConfiguration1.vue
        taskConfig1Ref.value?.openModal(rowData)
    }
}

const buildTree = (nodes, parentId = null) => {
    return nodes
        .filter(node => node.parentId === parentId)
        .map(node => {
            const children = buildTree(nodes, node.value);
            return {
                ...node,
                ...(children.length > 0 ? { children } : {})
            };
        });
}
const getArticleCategory = () => {
    service.get('/article/allCategory')
        .then(response => {
            const treeData = response.data?.map(item => ({
                label: item.name,
                value: item.id,
                parentId: item.parentId,
                alias: item.alias
            }));
            categoryOptions.value = buildTree(treeData);
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

const getSite = () => {
    service.get('/site/getAll')
        .then(response => {
            siteOptions.value = response?.data
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

const getlangCategory = () => {
    service.get('/lang/getAll')
        .then(response => {
            languageOptions.value = response?.data
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
}

const getAccount = () => {
    service.get('/user/getAll')
        .then(response => {
            accountNameOptions.value = response?.data
        })
        .catch(error => {
            ElMessage.error(error)
        });
}



onActivated(() => {
    getArticleCategory()
    getAccount()
    getlangCategory()
    getSite()
    getChoreographyData()
})

</script>

<style lang="scss">
.choreography-page {
    background-color: #fff;
    height: calc(100% - 10px);
    padding: 30px;
    width: 100%;
    box-sizing: border-box;

    .article-title {
        font-size: 20px;
        font-weight: 600;
    }

    .fliter {
        display: flex;
        align-items: center;
        margin: 30px 0;
        flex-wrap: wrap;
        gap: 10px 12px;
        /* 行列间距 */

        .filter-item {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
    }

    .el-button--primary {
        background-color: #1677ff;
    }

    .article-table {
        margin-top: 30px;
        height: calc(100% - 150px);
    }

    .el-drawer {
        width: 100% !important;
    }

    .el-drawer__body {
        padding: 0;
    }

    .el-table__row {
        font-size: 13px;
    }

    /* 折叠面板内容样式 */
    .collapse-content {
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        padding: 20px;
        background: white;
    }

    .collapse-content-wrapper {
        display: flex;
        flex-direction: column;
        gap: 20px;
        padding: 10px 20px;
    }

    .content-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .content-title {
        margin: 0;
        color: #303133;
        font-size: 16px;
        font-weight: 600;
    }

    .content-body {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 20px;
    }

    .article-outline {
        flex: 1;
    }

    .article-outline h5 {
        margin: 0 0 12px 0;
        color: #303133;
        font-size: 14px;
        font-weight: 600;
    }

    .outline-list {
        margin: 0;
        padding-left: 0;
    }

    .outline-list li {
        color: #606266;
        font-size: 14px;
        line-height: 1.5;
        margin-bottom: 4px;
        list-style: none;
    }

    .article-status {
        display: flex;
        flex-direction: column;
        gap: 8px;
        min-width: 200px;
    }

    .status-item {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .status-item .label {
        font-size: 14px;
        color: #909399;
    }

    .status-item .value {
        font-size: 14px;
        color: #303133;
    }

    .status-writing {
        color: #e6a23c !important;
        font-weight: 500;
    }

}
</style>
